import {createRouter, createWebHistory} from 'vue-router'
import {notification} from 'ant-design-vue';
import {useUserStore} from '@/stores/user';

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            name: 'main',
            component: () => import('../views/MainView.vue'),
            children: [
                {
                    path: '/welcome',
                    name: 'welcome',
                    component: () => import('../views/main/WelcomeView.vue')
                }, {
                    path: '/passenger',
                    name: 'passenger',
                    component: () => import('../views/main/PassengerView.vue')
                }
            ]
        },
        {
            path: '/login',
            name: 'login',
            component: () => import('../views/LoginView.vue'),
            meta: {
                noToken: true
            }
        }, {
            path: '',
            redirect: '/welcome'
        }
    ]
})

// 路由登录拦截
router.beforeEach((to, from, next) => {
    // 要不要对meta.noToken属性做监控拦截
    if (to.matched.some(function (item) {
        console.log(item, "是否不需要登录校验：", item.meta.noToken || false);
        return !item.meta.noToken
    })) {
        const {userInfo} = useUserStore()
        console.log("页面登录校验开始：", userInfo);
        if (!userInfo.token) {
            console.log("用户未登录或登录超时！");
            notification.error({description: "未登录或登录超时"});
            next('/login');
        } else {
            next();
        }
    } else {
        next();
    }
});

export default router
